<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告提示区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" show-icon type="warning" :closable="false">
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader clearable :options="catelist" :props="cateProps" v-model="selectedCateKeys"
            @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button :disabled='isBtnDisabled' @click='addParamsDialogViable = true' type='primary'>添加参数</el-button>
          <!-- 添加参数表格 -->
          <el-table :data="manyObjData" style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type='expand'>
              <!-- 渲染各个分类商品的参数 -->
              <template slot-scope='scope'>
                <el-tag @close='handleTagClosed(scope.row, i)' closable v-for='(item, i) in scope.row.attr_vals'
                  :key='i'>{{ item }}</el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInputRef" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type='index'></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope='scope'>
                <el-button type="primary" @click='showEditDialog(scope.row.attr_id)' icon="el-icon-edit">修改</el-button>
                <el-button type="danger" @click='showDeleteDialog(scope.row.attr_id)' icon="el-icon-delete">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button :disabled='isBtnDisabled' @click='addParamsDialogViable = true' type='primary'>添加属性</el-button>
          <!-- 添加参数表格 -->
          <el-table :data="onlyObjData" style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type='expand'>
              <!-- 渲染各个分类商品的参数 -->
              <template slot-scope='scope'>
                <el-tag @close='handleTagClosed(scope.row, i)' closable v-for='(item, i) in scope.row.attr_vals'
                  :key='i'>{{ item }}</el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInputRef" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type='index'></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope='scope'>
                <el-button type="primary" @click='showEditDialog(scope.row.attr_id)' icon="el-icon-edit">修改</el-button>
                <el-button type="danger" @click='showDeleteDialog(scope.row.attr_id)' icon="el-icon-delete">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog @close='addParamsDialogClosed' :title="'添加'+titleText" :visible.sync="addParamsDialogViable" width="50%">
      <!-- 表单 -->
      <el-form :model="addParamsForm" :rules="addParamsFormRules" ref="addParamsFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogViable = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog :title="'修改'+titleText" :visible.sync="editParamsDialogViable" width="50%">
      <!-- 表单 -->
      <el-form :model="editParamsForm" :rules="editParamsFormRules" ref="editParamsFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogViable = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        // 分类商品数据的数组
        catelist: [],
        // 父子关联的配置对象
        cateProps: {
          expandTrigger: 'hover',
          value: 'cat_id',
          label: 'cat_name',
          children: 'children'
        },
        // 选中项的分类id数组
        selectedCateKeys: [],
        // 被激活的页签名称
        activeName: 'only',
        // 动态参数的数据
        manyObjData: [],
        // 静态属性的数据
        onlyObjData: [],
        // 添加参数对话框的显示与隐藏
        addParamsDialogViable: false,
        // 添加参数表单数据
        addParamsForm: {
          attr_name: ''
        },
        // 添加参数表单验证规则
        addParamsFormRules: {
          attr_name: [{
            required: true,
            message: '请输入内容',
            trigger: 'blur'
          }]
        },
        // 修改参数表单数据
        editParamsForm: {},
        // 修改参数对话框的显示与隐藏
        editParamsDialogViable: false,
        // 修改参数对话框的表单校验规则
        editParamsFormRules: {
          attr_name: [{
            required: true,
            message: '请输入修改内容',
            trigger: 'blur'
          }]
        },
        // 控制添加参数表单显示与隐藏
        inputVisible: false,
        // 添加参数表单内容
        inputValue: ''
      }
    },
    created() {
      this.getCateList()
    },
    methods: {
      // 获取商品分类数据
      async getCateList() {
        const {
          data: res
        } = await this.$http.get('categories')
        if (res.meta.status !== 200) return this.$message.error('获取分类数据失败')

        console.log(res.data)
        this.catelist = res.data
      },
      // 监听级联选择框中选中项改变的事件
      handleChange() {
        // console.log(this.selectedCateKeys)
        // 判断选中的是否是第三级分类
        if (this.selectedCateKeys.length !== 3) {
          this.onlyObjData = []
          this.manyObjData = []
          this.selectedCateKeys = []
          return
        }
        console.log(this.selectedCateKeys.length)
        console.log(this.cateId)
        // 说明选中了三级分类
        // 发送请求获取分类商品的数据
        // 获取添加参数或添加属性的数据
        this.getParamsData()
      },
      // 监听被激活的页签改变的事件
      handleTabClick() {
        console.log(this.activeName)
        this.getParamsData()
      },
      // 获取参数数据
      async getParamsData() {
        // const {
        //   data: res
        // } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        //   params: {
        //     sel: 'only'
        //   }
        // })
        const {
          data: res
        } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: this.activeName
          }
        })
        console.log(res.data)
        if (res.meta.status !== 200) return this.$message.error('获取参数失败')
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          // 控制文本框的显示与隐藏
          item.inputVisible = false
          // 文本框中输入的值
          item.inputValue = ''
        })
        if (this.activeName === 'many') {
          this.manyObjData = res.data
        } else {
          this.onlyObjData = res.data
        }
      },
      // 监听添加参数的事件
      addParams() {
        // 表单预校验，发送请求，添加参数
        this.$refs.addParamsFormRef.validate(async valid => {
          if (!valid) return
          const {
            data: res
          } = await this.$http.post(`categories/${this.cateId}/attributes`, {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName
          })
          if (res.meta.status !== 201) return this.$message.error('添加参数失败')
          // 添加参数成功
          this.$message.success('添加参数成功')
          // 刷新参数列表
          this.getParamsData()
        })
        // 隐藏添加参数对话框
        this.addParamsDialogViable = false
      },
      // 监听添加参数对话框的关闭事件
      addParamsDialogClosed() {
        this.$refs.addParamsFormRef.resetFields()
      },
      // 监听修改对话框展示事件
      async showEditDialog(attrId) {
        console.log(attrId)
        // 根据id查询当前商品分类的信息数据
        const {
          data: res
        } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, {
          params: {
            sel: this.activeName
          }
        })
        if (res.meta.status !== 200) return this.$message.error('查询参数信息失败')
        // 获取成功
        this.$message.success('获取参数成功')
        // 将数据保存在data中
        this.editParamsForm = res.data
        // 显示修改参数的对话框
        this.editParamsDialogViable = true
      },
      // 修改参数
      editParams() {
        // 表单预校验
        this.$refs.editParamsFormRef.validate(async valid => {
          if (!valid) return
          // 发送网络请求修改参数
          const {
            data: res
          } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
            params: {
              attr_sel: this.activeName,
              attr_name: this.editParamsForm.attr_name
            }
          })
          if (res.meta.status !== 200) return this.$message.error('修改参数失败')
          // 修改参数成功
          this.$message.success('修改参数成功')
          // 刷新参数列表
          this.getParamsData()
        })
        // 隐藏对话框
        this.editParamsDialogViable = false
      },
      // 删除参数
      async showDeleteDialog(attrId) {
        const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (confirmResult !== 'confirm') {
          return this.$message.info('取消了删除')
        }
        // 发起请求删除参数
        const {
          data: res
        } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
        if (res.meta.status !== 200) return this.$message.error('删除参数失败')
        // 删除成功
        this.$message.success('删除成功')
        // 刷新参数列表
        this.getParamsData()
      },
      // 监听键盘抬起和失去焦点的事件
      async handleInputConfirm(row) {
        // 判断输入内容是否为空或者空格
        if (row.inputValue.trim().length === 0) {
          // 隐藏表单
          row.inputVisible = false
          row.inputValue = ''
          return
        }
        // 用户输入内容信息
        // 保存输入内容到当前的attr_vals数组中
        row.attr_vals.push(row.inputValue.trim())
        // 隐藏表单
        row.inputVisible = false
        row.inputValue = ''
        // 修改数据保存到数据库
        this.saveAttrValues(row)
      },
      // 是否显示添加参数输入框
      showInput(row) {
        // 显示表单
        row.inputVisible = true
        // 自动获取焦点
        this.$nextTick(_ => {
          this.$refs.saveTagInputRef.$refs.input.focus()
        })
      },
      // 保存参数信息，发送请求
      async saveAttrValues(row) {
        // 发起请求保存修改的参数信息
        const {
          data: res
        } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        })

        if (res.meta.status !== 200) return this.$message.error('修改参数失败')

        // 修改参数成功
        this.$message.success('修改参数成功')
      },
      // 监听点击tag标签删除的事件
      handleTagClosed(row, i) {
        // 删除点击的tag标签参数数据信息
        row.attr_vals.splice(i, 1)
        // 发送请求修改数据
        this.saveAttrValues(row)
      }
    },
    computed: {
      // 添加参数或添加属性按钮是否禁用
      isBtnDisabled() {
        if (this.selectedCateKeys.length === 3) {
          return false
        } else {
          return true
        }
      },
      // 分类id
      cateId() {
        if (this.selectedCateKeys.length === 3) {
          return this.selectedCateKeys[2]
        }
        return null
      },
      // 添加参数对话跨康的显示文本
      titleText() {
        if (this.activeName === 'many') {
          return '动态参数'
        }
        return '静态属性'
      }
    }
  }

</script>
<style lang='less' scoped>
  .el-card {
    margin-top: 20px;
  }

  .el-alert {
    margin-bottom: 15px;
  }

  element.style {
    top: 0 !important;
  }

  .el-tag {
    margin: 5px;
  }

  .input-new-tag {
    width: 90px;
  }

</style>
